package com.hardson.toolkit.swing.jbutton;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;

import javax.swing.JButton;
import javax.swing.JFrame;

public class RoundButton extends JButton {

	private static final long serialVersionUID = 1L;

	public RoundButton(final String label) {

		super(label);

		// 下面的语句讲述这个按钮变为一个圆形而不是椭圆形

		Dimension size = this.getPreferredSize();

		size.width = size.height = Math.max(size.width, size.height);

		this.setPreferredSize(size);

		// 不让JButton画背景而允许我们去画一个圆背景

		this.setContentAreaFilled(false);

	}

	// 画出圆的背景和标签

	@Override
	protected void paintComponent(final Graphics g) {

		if (this.getModel().isArmed()) {

			g.setColor(Color.lightGray);

		} else {

			g.setColor(this.getBackground());

		}

		g.fillOval(0, 0, this.getSize().width - 1, this.getSize().height - 1);

		// 在焦点上画出一个标签

		super.paintComponent(g);

	}

	// 画出一个边框

	@Override
	protected void paintBorder(final Graphics g) {

		g.setColor(this.getForeground());

		g.drawOval(0, 0, this.getSize().width - 1, this.getSize().height - 1);

	}

	// 侦察单击区域

	Shape shape;

	@Override
	public boolean contains(final int x, final int y) {

		// 如果按钮改变了尺寸将重新创建一个Shape

		if (this.shape == null || !this.shape.getBounds().equals(this.getBounds())) {

			this.shape = new Ellipse2D.Float(0, 0, this.getWidth(), this.getHeight());

		}

		return this.shape.contains(x, y);

	}

	// 测试

	public static void main(final String[] args) {

		JButton button1 = new RoundButton("http://www.cn-java.com");

		JButton button2 = new RoundButton("欢迎你常来做客");

		button1.setBackground(Color.green);

		button2.setBackground(Color.yellow);

		// 创建一个Fram来显示这个按钮

		JFrame frame = new JFrame();

		frame.getContentPane().add(button1);

		frame.getContentPane().add(button2);

		frame.getContentPane().setLayout(new FlowLayout());

		frame.setSize(450, 350);

		frame.setVisible(true);

		// 测试单击事件

		button1.addActionListener(new ActionListener() {

			public void actionPerformed(final ActionEvent e) {

				System.out.println("you click button1!");

			}

		});

		button2.addActionListener(new ActionListener() {

			public void actionPerformed(final ActionEvent e) {

				System.out.println("you click button2!");

			}

		});

	}

}
